/* 
 * File: xmlpersister.cpp
 * Project: QTimeTracker
 * Author: Steve Sindelar, http://stevesindelar.cz
 * Licence: NewBSD licence.
 */

#include "xmlpersister.h"
#include <QString>
#include <QDomDocument>
#include <QDomElement>
#include <QTextStream>
#include <QFile>
#include <QXmlDefaultHandler>
#include <QXmlSimpleReader>
#include "loadxmlhandler.h"

using namespace Core;

XmlPersister::XmlPersister(QString filename)
{
    this->filename = filename;
}

void XmlPersister::save(QList<Item*> items) 
{
    QDomDocument document("items");
    QDomElement root = document.createElement("items");
    document.appendChild(root);

    foreach(Item* item, items)
    {
        QDomElement itemElement = document.createElement("item");
        root.appendChild(itemElement);
        itemElement.setAttribute("name", item->name);
        itemElement.setAttribute("note", item->note);
        foreach(TimeSpan span, item->timeSpans)
        {
            TimeSpanData data = span.getLength();
            QDomElement spanElement = document.createElement("span");
            itemElement.appendChild(spanElement);
            spanElement.setAttribute("from", span.getFrom().toString(/*"dd.MM.yyyy hh:mm:ss"*/Qt::ISODate));
            QString time = QString("%1:%2:%3").arg(data.hours).arg(data.minutes).arg(data.seconds);
            spanElement.setAttribute("time", time);
            spanElement.setAttribute("note", span.note);
        }
    }

    QFile file(this->filename);
    file.open(QIODevice::WriteOnly | QIODevice::Truncate);    
    QString result = document.toString();
    file.write(result.toUtf8());
    file.flush();
    file.close();
}

QList<Item*> XmlPersister::load()
{
    QXmlSimpleReader reader;
    QFile file(this->filename);
    file.open(QIODevice::ReadOnly);
    QXmlInputSource* source = new QXmlInputSource(&file);
    LoadXmlHandler* handler = new LoadXmlHandler();

    reader.setContentHandler(handler);
    if (!reader.parse(source))
    {
        throw std::exception(handler->errorMessage.toLatin1().data());
    }

    QList<Item*> result = handler->result;
    delete handler;
    delete source;
    return result;
}
